import store from "@/store"
import {dynamicRoutes} from "./route";

const dynamicRoutesList = [
    {
        path: '/',
        name: '/',
        component: 'layout/index',
        redirect: '/home',
        meta: {
            isKeepAlive: true,
        },
        children: [],
    },
]

// 加载路由
export async function getRouterList(router, to, next) {
    store.dispatch('routesList/setRoutesList', setFilterMenuFun(dynamicRoutes, store.state.user.permissions));
    dynamicRoutesList[0].children =dynamicRoutes
    const awaitRoute = await dynamicRouter(dynamicRoutesList);
    [...awaitRoute, { path: '*', redirect: '/404' }].forEach((route) => {
        router.addRoute({ ...route });
    });
    setCacheTagsViewRoutes(dynamicRoutesList);
    next({ ...to, replace: true });

}

// 缓存多级嵌套数组处理后的一维数组(tagsView、菜单搜索中使用：未过滤隐藏的(isHide))
export function setCacheTagsViewRoutes(arr) {
    // 先处理有权限的路由，否则 tagsView、菜单搜索中无权限的路由也将显示
    let rolesRoutes = setFilterMenuFun(arr, store.state.user.permissions);
    // 添加到 vuex setTagsViewRoutes 中
    store.dispatch('tagsViewRoutes/setTagsViewRoutes', formatTwoStageRoutes(formatFlatteningRoutes(rolesRoutes)));
}

// 多级嵌套数组处理成一维数组
export function formatFlatteningRoutes(arr) {
    if (arr.length <= 0) return false;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].children) {
            arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
        }
    }
    return arr;
}

// 处理 tagsViewList 数据，默认路由全部缓存
// isKeepAlive 处理 `name` 值，进行路由缓存
export function formatTwoStageRoutes(arr) {
    if (arr.length <= 0) return false;
    const newArr = [];
    const cacheList = [];
    arr.forEach((v) => {
        newArr.push({ ...v });
        cacheList.push(v.name);
        store.dispatch('keepAliveNames/setCacheKeepAlive', cacheList);
    });
    return newArr;
}


// 判断路由 meta.permissions 中是否包含当前登录用户权限字段
export function hasPermission(permissions, route) {
    if (route.meta && route.meta.permissions) return permissions.some((permission) => route.meta.permissions.includes(permission));
    else return true
}

// 递归过滤有权限的路由
export function setFilterMenuFun(routes, permissions) {
    const menu = [];
    routes.forEach((route) => {
        const item = { ...route };
        if (hasPermission(permissions, item)) {
            if (item.children) item.children = setFilterMenuFun(item.children, permissions);
            menu.push(item);
        }
    });
    return menu;
}

// 处理后端返回的 `component` 路径，拼装实现懒加载
export function loadView(path) {
    /**
     * 打包成一个 js、一个 css
     */
    // if (path.indexOf('layout') > -1) return () => Promise.resolve(require(`@/${path}`));
    // else return () => Promise.resolve(require(`@/views/${path}`));

    /**
     * 打包成多个 js、多个 css
     */
    if (path.indexOf('layout') > -1) return () => import(`@/${path}`);
    else return () => import(`@/views/${path}`);
}

// 递归处理每一项 `component` 中的路径
export function dynamicRouter(routes) {
    return routes.map((view) => {
        if (view.component) view.component = loadView(view.component);
        if (view.children) dynamicRouter(view.children);
        return view;
    });
}
